let treeData = formatDataTree(data)
// console.log(treeData)

function formatDataTree(data) {
  let parents = data.filter(p => p.pid === 0),
      children = data.filter(c => c.pid !== 0);

      dataToTree(parents, children)
  return parents;
}
// @params array[] parents, children 
function dataToTree(parents, children) {
  parents.map(p => {
    children.map((c, i)=> {
      if(c.pid === p.id) {

        let _children = JSON.parse(JSON.stringify(children))
        _children.splice(i, 1)
        dataToTree([c], _children)
        
        if(p.children) {
          p.children.push(c)
        } else {
          p.children = [c];
        }
      }
    })
  })
}

// 非递归扁平化处理
function formatDataTree2(data) {
  let _data = JSON.parse(JSON.stringify(data));
  return _data.filter(p => {
    const _arr = _data.filter(c => c.pid === p.id);
    _arr.length && (p.children = _arr)
    return p.pid === 0;
  })
}
// console.log(formatDataTree2(data))

treeData.filter((t, i) => {
  const key = '0-' + i;
  t['key'] = key
  if(t.children) {
    treeAddId(t.children, key)
  }
})

function treeAddId (t, key) {
  for (let i = 0; i < t.length; i++) {
    const keyId = key + '-' + i
    t[i]['key'] = keyId;
    if(t[i].children) {
      treeAddId(t[i].children, keyId)
    }
  }
}
console.log(treeData,'treeData')
